<template>
  <div class="app-container">
    <div class="filter-container">


      <el-radio-group v-model="listQuery.status" style="margin-left: 5px" class="filter-item" @change="getList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="1">正常</el-radio-button>
        <el-radio-button :label="2">禁用</el-radio-button>
      </el-radio-group>

      <el-upload
          style="float: right;margin-right:10px;margin-top:5px"
          class="upload-demo"
          ref="upload"
          :action="'/api/card/batch_create'"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="excelSuccess"
          :before-remove="beforeRemove"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
          :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>
      <!--      <el-date-picker-->
      <!--          class="filter-item"-->
      <!--          v-model="listQuery.time"-->
      <!--          type="datetimerange"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          :picker-options="pickerOptions"-->
      <!--          range-separator="至"-->
      <!--          start-placeholder="注册时间范围(小)"-->
      <!--          end-placeholder="注册时间范围(大)"-->
      <!--          @change="getList"-->
      <!--          align="right"-->
      <!--      >-->
      <!--      </el-date-picker>-->
      <el-input
          class="filter-item"
          placeholder="卡号搜索"
          v-model="listQuery.sn"
          style="width: 20%;margin-left: 5px"
          @keyup.enter.native="getList"
      >
      </el-input>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>

    </div>
    <el-checkbox-group v-model="checkedIds" @change="handleCheckedIdsChange">
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
        <el-table-column align="center" label="ID" min-width="80">
          <template slot-scope="scope">
            <el-checkbox :key="scope.row.id" :label="scope.row.id"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column min-width="80" align="center" label="卡号">
          <template slot-scope="scope">
            <el-link type="primary">{{ scope.row.card_no }}</el-link>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
        <el-table-column min-width="80" align="center" label="余额">
          <template slot-scope="scope">
            <el-link type="success">{{ scope.row.amount }}</el-link>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>


        <el-table-column min-width="55" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="2"
                @change="changeStatus($event,scope.row.id)"

            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column min-width="80" align="center" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" split-button type="primary"
                         @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" style="margin-left:5px"
                       @click="del(scope.row.id)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-checkbox-group>
    <el-divider>
      <el-checkbox :indeterminate="isIndeterminate" style="margin-left:10px;" v-model="checkAll"
                   @change="handleCheckAllChange"
      >全选
      </el-checkbox>
      <el-button type="primary" size="mini" round style="margin-left:10px;" @click="batchShow">批量修改</el-button>
    </el-divider>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog title="批量余额" :visible.sync="dialogBatchVisible" width="50%">
      <el-form ref="dataForm" :rules="rules" label-position="left" label-width="120px"
               style="width: 90%; margin-left:5%;"
      >
        <el-form-item label="余额">
          <el-input v-model="now_amount"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button type="primary" @click="batchChange()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 90%; margin-left:5%;"
      >
        <el-form-item label="卡号" prop="card_no">
          <el-input v-model="temp.card_no" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="余额" >
          <el-input v-model="temp.amount" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="temp.status"
              :active-value="1"
              :inactive-value="0"
              active-text="开启"
              inactive-text="关闭">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>


<!--    <el-drawer-->
<!--        :title="'设备'+now_sn+'最近20条信号记录'"-->
<!--        :visible.sync="signalDraw"-->
<!--    >-->
<!--      <template>-->
<!--        <el-card>-->
<!--          <el-table-->
<!--              stripe-->
<!--              :data="signalData"-->
<!--              style="width: 100%">-->
<!--            <el-table-column-->
<!--                prop="signal"-->
<!--                label="信号值"-->
<!--                width="80">-->
<!--            </el-table-column>-->
<!--            <el-table-column-->
<!--                prop="created_at"-->
<!--                label="上报时间"-->
<!--                width="180">-->
<!--            </el-table-column>-->
<!--          </el-table>-->
<!--        </el-card>-->
<!--      </template>-->
<!--    </el-drawer>-->

  </div>
</template>

<script>
import {
  getList,
  create,
  del,
  changeStatus,
  batchChange,
} from '@/api/card'
import Pagination from '@/components/Pagination'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import cityData from '@/assets/pca-code.json'

export default {
  name: 'CardList',
  components: {Pagination, ImageCropper, PanThumb},
  computed: {
    // contentShortLength() {
    //   return this.temp.introduction .length
    // },
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 12) {
        return value.slice(0, 12) + '...'
      }
      return value
    }
  },
  data() {
    return {
      info: [],
      dialogBatchVisible: false,
      dialogParamsVisible: false,
      dialogPortVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      checkAll: false,
      idOptions: [],
      isIndeterminate: true,
      checkedIds: [],
      dialogImgVisible: false,
      imagecropperShow: false,
      imagecropperKey: 0,
      now_amount:'',
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        card_no: '',
        status: ''
      },

      temp: {
        id: undefined,
        card_no: '',
        amount: '',
        status: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      portDrawer: false,
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        card_no: [{required: true, message: '设备编号不能为空', trigger: 'blur'}],
        amount: [{required: true, message: '余额不能为空', trigger: 'blur'}],
      },
      addr: [],
      options: cityData,
      nowDistributor: '',
      disOptions: [],
      cityProps: {
        value: 'code',   // 指定选项的 值 为选项对象的某个属性值
        label: 'name',   // 指定选项 标签 为选项对象的某个属性值
        children: 'children'    //指定选项的 子选项 为选项对象的某个属性值
      },
      colors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {

  },
  created() {
    this.getList()
  },
  methods: {
    batchShow() {
      this.dialogBatchVisible = true
    },
    batchChange() {
      if (this.checkedIds.length <= 0) {
        this.$message.info('请先选中要回传的数据')
        return ''
      }
      let json = JSON.stringify(this.checkedIds)
      batchChange(json, this.now_amount).then(response => {
        if (response.code == 200) {
          this.dialogBatchVisible = false
          this.$notify.success({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.msg,
            duration: 2000
          })
        }
      })
      // let search = JSON.stringify(this.listQuery)
      // window.open('/api/excel/export_sign?data=' + json+'&search='+search)
    },
    handleCheckedIdsChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.idOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.idOptions.length
    },
    handleCheckAllChange(val) {
      this.checkedIds = val ? this.idOptions : []
      this.isIndeterminate = false
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    excelSuccess(file, fileList) {
      if (file.code == 200) {
        this.$message.success('导入成功')
        this.getList()
      } else {
        this.$message.info(file.msg)
      }
      this.fileList = []
    },
    handlePreview(file) {

    },
    handleRemove(file, fileList) {

    },
    changeStatus(val, id) {
      changeStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
        this.getList()
      })
    },
    increase() {
      this.temp.rate += 5;
      if (this.temp.rate > 100) {
        this.temp.rate = 100;
      }
    },
    decrease() {
      this.temp.rate -= 5;
      if (this.temp.rate < 0) {
        this.temp.rate = 0;
      }
    },
    handleAddrChange(e) {
      // 获取当前选中节点的数组
      let addrNode = this.$refs['cascaderAddr'].getCheckedNodes()[0]
      let addrText = addrNode.pathLabels
      this.temp.province_name = addrText[0]
      this.temp.city_name = addrText[1]
      this.temp.area_name = addrText[2]
    },
    handleDistributorsChange(e) {
      this.editStation()
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
        this.idOptions = []
        this.checkedIds = []
        for (var i in this.list) {
          this.idOptions[i] = this.list[i].id
        }
      })
    },
    resetForm() {
      this.dialogFormVisible = false
    },
    async handleCreate() {
      this.resetTemp()
      // this.getSelector()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    async handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        card_no: '',
        amount: '',
        status: 1
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
